<?php

namespace hyf2599\Duanxinyun;
use hyf2599\SmsServiceInterface;
use think\facade\Log;

class DuanxinyunSmsService implements SmsServiceInterface {
    private $appkey;
    private $appcode;
    private $appsecret;
	private $baseurl = 'http://101.37.35.20:9090';

    public function __construct()
	{
		$this->appkey = config('my.duanxinyun_sms_appkey');
		$this->appcode = config('my.duanxinyun_sms_appcode');
		$this->appsecret = config('my.duanxinyun_sms_appsecret');
	}

	public function sendSms($phone, $msg) {
        try {
            $httpClient = new \GuzzleHttp\Client();
            $url = "$this->baseurl/sms/batch/v1";

            $timestamp = $this->getMillisecond();
            $sign = md5($this->appkey . $this->appsecret . $timestamp);
            $extend = '';

            $data = [
                'appkey' => $this->appkey,
                'appcode' => $this->appcode,
                'timestamp' => $timestamp,
                'phone' => $phone,
                'msg' => $msg,
                'sign' => $sign,
                'extend' => $extend
            ];
            $response = $httpClient->post($url, [
                'json' => $data,
                'headers' => [
                    'Content-Type' => 'application/json; charset=UTF-8'
                ]
            ]);

            $res = json_decode($response->getBody()->getContents(), 1);
            if ($res['code'] != '00000')
                throw new \Exception($res['desc']);
            return ['code' => 0, 'msg' => '发送成功'];

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            throw $e;
        }
    }

    function getMillisecond(): int
    {
        list($microsecond, $time) = explode(' ', microtime());
        return (int)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
    }
}

?>
